import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { message } from 'antd';
import { ApiResponse } from '@/types/common';

// 请求配置接口
export interface RequestConfig extends AxiosRequestConfig {
  skipAuth?: boolean;
  skipErrorHandler?: boolean;
}

class Request {
  public instance: AxiosInstance;

  constructor() {
    // 创建axios实例
    this.instance = axios.create({
      baseURL: '/instrument',
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 添加认证token
        const token = localStorage.getItem('token');
        if (token && config.headers) {
          config.headers.Authorization = `${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        return response;
      },
      (error) => {
        // 处理HTTP错误
        if (error.response) {
          const { status, data } = error.response;
          
          switch (status) {
            case 401:
              // 未授权，清除token并跳转登录
              localStorage.removeItem('token');
              localStorage.removeItem('refreshToken');
              localStorage.removeItem('userInfo');
              if (window.location.pathname !== '/login') {
                window.location.href = '/login';
              }
              break;
            case 403:
              message.error('权限不足');
              break;
            case 404:
              message.error('资源不存在');
              break;
            case 500:
              message.error('服务器错误');
              break;
            default:
              message.error(data?.message || '网络错误');
          }
        } else if (error.request) {
          message.error('网络连接失败');
        } else {
          message.error(error.message || '请求失败');
        }
        
        return Promise.reject(error);
      }
    );
  }

  // GET请求
  async get<T = unknown>(url: string, config?: RequestConfig): Promise<T> {
    const response = await this.instance.get(url, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.message || '请求失败');
  }

  // POST请求
  async post<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<T> {
    const response = await this.instance.post(url, data, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.message || '请求失败');
  }

  // PUT请求
  async put<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<T> {
    const response = await this.instance.put(url, data, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.message || '请求失败');
  }

  // DELETE请求
  async delete<T = unknown>(url: string, config?: RequestConfig): Promise<T> {
    const response = await this.instance.delete(url, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.message || '请求失败');
  }

  // PATCH请求
  async patch<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<T> {
    const response = await this.instance.patch(url, data, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.message || '请求失败');
  }

  // 上传文件
  async upload<T = unknown>(url: string, formData: FormData, config?: RequestConfig): Promise<T> {
    const response = await this.instance.post(url, formData, {
      ...config,
      headers: {
        'Content-Type': 'multipart/form-data',
        ...config?.headers,
      },
    });
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.message || '请求失败');
  }
}

// 创建请求实例
const request = new Request();

// 创建API客户端实例
export const apiClient = {
  get: <T>(url: string, params?: Record<string, unknown>): Promise<ApiResponse<T>> =>
    request.instance.get(url, { params }).then(res => res.data),
  
  post: <T>(url: string, data?: unknown): Promise<ApiResponse<T>> =>
    request.instance.post(url, data).then(res => res.data),
  
  put: <T>(url: string, data?: unknown): Promise<ApiResponse<T>> =>
    request.instance.put(url, data).then(res => res.data),
  
  delete: <T>(url: string): Promise<ApiResponse<T>> =>
    request.instance.delete(url).then(res => res.data),
  
  patch: <T>(url: string, data?: unknown): Promise<ApiResponse<T>> =>
    request.instance.patch(url, data).then(res => res.data),
};

// 导出单独的方法，方便直接使用
export const get = request.get.bind(request);
export const post = request.post.bind(request);
export const put = request.put.bind(request);
export const del = request.delete.bind(request);
export const patch = request.patch.bind(request);
export const upload = request.upload.bind(request);

export default request; 